from Crypto.Cipher import AES
from Crypto.Util import Padding
import socket
import json
import binascii

HOST = '127.0.0.1'
PORT = 65432

# 定义加密密钥和初始向量
key = b'\r\xa3ki\t$\n\xab\n\xf7\xf0\xd5?\x9e\xccP'
iv = b'\x8d\x9a\xe7f\x18\xe2Z\xd2x\x11\x1e\x91\xc6\x89d\xb0'

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    print('Listening on', (HOST, PORT))
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        data = b''
        while True:
            chunk = conn.recv(4096)
            if not chunk:
                break
            data += chunk
        # 解析JSON数据
        student = json.loads(data.decode('utf-8'))

        # 将十六进制字符串转换为加密后的图像数据
        image_data_encrypted = binascii.unhexlify(student['image'])

        # 创建AES解密模块
        cipher = AES.new(key, AES.MODE_CBC, iv)

        # 对加密后的图像数据进行解密
        image_data_padded = cipher.decrypt(image_data_encrypted)
        image_data_decrypted = Padding.unpad(image_data_padded, AES.block_size)

        # 将解密后的图像数据写入名为photo.png的文件中
        with open('photo.png', 'wb') as f:
            f.write(image_data_decrypted)
        print('Saved image file: photo.png')